package com.ifengchao.service.impl;

import com.ifengchao.commonUtil.ServiceException;
import com.ifengchao.dao.iface.DealActAccountDao;
import com.ifengchao.dao.iface.DealOrderDao;
import com.ifengchao.pojo.AdverHourBean;
import com.ifengchao.pojo.Order;
import com.ifengchao.service.DealOrderService;
import com.ifengchao.util.zzy.ZhiZiYunUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单处理
 *
 * @author chen
 */
@Service
public class DealOrderServiceImpl implements DealOrderService {

    private static final Logger logger = Logger.getLogger(DealOrderServiceImpl.class);

    @Autowired(required = true)
    private DealOrderDao dealOrderDao;

    @Autowired(required = true)
    private DealActAccountDao dealActAccountDao;

    /**
     * 查询所有订单
     */
    @Override
    public List<Order> queryAllOrder() throws ServiceException {
        logger.info("查询所有订单");
        return dealOrderDao.queryAllOrder();
    }

    /**
     * 插入所有符合条件的计划
     */
    @Override
    public void dealAllPlan() throws ServiceException {
        // 查询有效广告主id
        List<String> planIdList = dealOrderDao.queryAllAdvertise();
        String[] planArr = planIdList.toArray(new String[planIdList.size()]);
        Calendar starttime = Calendar.getInstance();
        starttime.add(Calendar.DAY_OF_MONTH, -1);
        //获取当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endtime = sdf.format(new Date());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("advertiserids", planArr);
        paramMap.put("starttime", sdf.format(starttime.getTime()));
        paramMap.put("endtime", endtime);
        for (int n = 0; n < 2; n++) {
            if(n==0){
                paramMap.put("platform", 1);//pc
            } else {
                paramMap.put("platform", 2);//移动
            }
            JSONObject planResult = new JSONObject();
            try {
                planResult = ZhiZiYunUtil.getZhiZiYunData("rtbreport/getHoursBySite", paramMap);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("调用智子云接口失败，原因：", e);
            }
            if (null != planResult && (Boolean) planResult.get("status")) {
                List<String> adList = new ArrayList<>();
                JSONObject planObj = planResult.getJSONObject("response");
                Iterator it = planObj.keySet().iterator();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    JSONArray dataArray = planObj.getJSONArray(key);
                    if (dataArray.size() > 0)
                        adList.add(key);
                }
                for (int i = 0; i < adList.size(); i++) {
                    JSONArray obj = planObj.getJSONArray(adList.get(i));
                    List<AdverHourBean> adverHourList1 = obj.toList(obj, AdverHourBean.class);
                    for (AdverHourBean planBean : adverHourList1) {
                        Calendar now = Calendar.getInstance();
                        now.add(Calendar.HOUR_OF_DAY, -5);
                        SimpleDateFormat sdfhh = new SimpleDateFormat("yyyy-MM-dd HH");
                        Date date_01 = new Date();
                        Date date_02 = date_01;
                        try {
                            date_01 = sdfhh.parse(planBean.getStatDate()+" "+ planBean.getHour());
                            date_02 = sdfhh.parse(sdfhh.format(now.getTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                            logger.error("字符串转日期格式异常，原因：", e);
                        }
                        if (date_01.compareTo(date_02) == 0) {
                            Map<String, Object> selMap = dealOrderDao.selAdvertiseMsg(planBean.getAdvertiserid());
                            if (null == selMap) {
                                logger.error("该广告主信息不存在！advertiseId：" + planBean.getAdvertiserid());
                                continue;
                            }
                            planBean.setServiceFee(String.valueOf(selMap.get("serviceFee")));
                            planBean.setFcadvertiseid(String.valueOf(selMap.get("adveterId")));
                            System.out.println("准备插入订单数据,广告主id="+selMap.get("adveterId"));
                            if(new BigDecimal(planBean.getTotalCost()).compareTo(new BigDecimal(0))>0) {
                                dealOrderDao.insertPlanList(planBean);
                            }
                        }
                    }
                }
            }
        }
    }
}
